const fs = require('fs');
const path = require('path');

const isNeedPack = (() => {
    const configPath = path.resolve(__dirname, './../pack.log');
    let configDir = [];
    if (fs.existsSync(configPath) && fs.statSync(configPath).isFile()) {
        configDir = fs.readFileSync(configPath, 'utf8').split(/\s+/).map(i => i.trim()).filter(i => i)
    }
    const needPackDir = [
        'main',
        ...configDir,
    ];
    return function (P) {
        return configDir.length < 1 ? true : needPackDir.some(item => P.indexOf(item) > -1);
    };
})();

module.exports = function getEntriesRouter({ baseUrl, srcPath, distPath }, ignoreNeedPack) {
    const entries = {};
    let routers = {};
    const ROOT_PATH_LEN = path.resolve(baseUrl, srcPath).length + 1;

    function handleDir(dir) {
        if (fs.statSync(dir).isDirectory()) {
            const dirNames = fs.readdirSync(dir).map(item => path.resolve(dir, item));
            dirNames.forEach((item) => {
                const STAT = fs.statSync(item);
                if (STAT.isFile() && /\/View.js$/.test(item)) {
                    if (!ignoreNeedPack && !isNeedPack(item)) {
                        return;
                    }
                    const entryKey = item.slice(ROOT_PATH_LEN).split('/').slice(0, -1).join('/');
                    entries[entryKey] = item;

                    const FILE_CONTENT = fs.readFileSync(item, 'utf8');

                    FILE_CONTENT.replace(/\n\s*WPT.allPage\[['"](.+)['"]\]/g, (matchStr, $0) => {
                        routers[$0] = `/webApp/${distPath}/${entryKey}.js`.replace(/\/+/g, '/');
                    });
                } else if (STAT.isDirectory()) {
                    handleDir(item);
                }
            });
        }
    }

    handleDir(srcPath);
    // 手动添加对main的支持
    routers = Object.assign({}, routers, {
        main: `/webApp/${distPath}/main.js`.replace(/\/+/g, '/'),
        // automationTest: `/webApp/${distPath}/views/automationTest.js`.replace(/\/+/g, '/'),
    });
    return {
        entries,
        routers
    };
};
